package com.feige.utils;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author feige
 */
@Component
public class FastdfsUtils {

    public static final String[] EXTENSIONS = {"png","gif","jpg","jpeg"};
    public static final String BLOB = "BLOB";

    @Resource
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 判断用户上传的文件格式是否合法
     * @param extension
     * @return
     */
    public boolean isOk(String extension){
        for (String s : EXTENSIONS) {
            if (s.equalsIgnoreCase(extension)){
                return true;
            }
        }
        return false;
    }

    /**
     * 上传
     * @param file
     * @return
     * @throws IOException
     */
    public StorePath upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        if (BLOB.equalsIgnoreCase(originalFilename)){
            extension = EXTENSIONS[0];
        }
        if(isOk(extension)){
            // 上传
            return fastFileStorageClient.uploadFile(
                    file.getInputStream(), file.getSize(),
                    extension,
                    null);
        }else {
            return null;
        }

    }

    /**
     * 删除
     * @param path
     */
    public void delete(String path) {
        fastFileStorageClient.deleteFile(path);
    }

    /**
     * 删除
     * @param group
     * @param path
     */
    public void delete(String group,String path) {
        fastFileStorageClient.deleteFile(group,path);
    }

    /**
     * 文件下载
     * @param path 文件路径，例如：group1/M00/00/00/rBEAAl6yXtiAarTtAAAQg9ci7ck503.png
     * @return
     */
    public void download(String path, HttpServletResponse response) throws IOException {
        // 获取文件
        StorePath storePath = StorePath.parseFromUrl(path);
        String filename = FilenameUtils.getName(storePath.getPath());
        byte[] bytes = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
        response.reset();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.close();
    }
}
